import { defineStore } from 'pinia'
import { useQuery, useMutation } from '@tanstack/vue-query'
import api from '../api'

export const useFamilyTreeStore = defineStore('familyTree', {
  state: () => ({
    familyTrees: [],
    familyMembers: [],
    selectedFamilyTree: null,
    generations: []
  }),
  
  getters: {
    getFamilyTrees: (state) => state.familyTrees,
    getFamilyMembers: (state) => state.familyMembers,
    getSelectedFamilyTree: (state) => state.selectedFamilyTree,
    getGenerations: (state) => state.generations
  },
  
  actions: {
    // 获取家族树列表的 useQuery 配置
    useFetchFamilyTrees() {
      return useQuery({
        queryKey: ['family-trees'],
        queryFn: () => api.get('/family-trees'),
        onSuccess: (result) => {
          this.familyTrees = result.data.data || []
        },
        onError: (error) => {
          console.error('获取家族树列表失败:', error)
        }
      })
    },
    
    // 创建家族树的 useMutation 配置
    useCreateFamilyTree() {
      return useMutation({
        mutationFn: (treeData) => api.post('/family-trees', treeData),
        onError: (error) => {
          console.error('创建家族树失败:', error)
        }
      })
    },
    
    // 根据家族树获取成员的 useQuery 配置
    useFetchFamilyMembersByTree() {
      return useQuery({
        queryKey: ['family-members', 'family-tree', this.selectedFamilyTree],
        queryFn: () => api.get(`/members/family-tree/${this.selectedFamilyTree}`),
        enabled: !!this.selectedFamilyTree,
        onSuccess: (result) => {
          this.familyMembers = result.data.data || []
        },
        onError: (error) => {
          console.error('加载家族树数据失败:', error)
        }
      })
    },
    
    // 加载家族树数据
    async loadFamilyTreeData(familyTreeId) {
      try {
        this.setSelectedFamilyTree(familyTreeId)
        // 获取家族树的所有成员
        const response = await api.get(`/members/family-tree/${familyTreeId}`)
        if (response.data.data) {
          this.familyMembers = response.data.data
          // 根据成员关系计算代数
          this.calculateGenerations()
        }
        return { success: true }
      } catch (error) {
        console.error('加载家族树数据失败:', error)
        return { success: false, message: '加载家族树数据失败' }
      }
    },
    
    // 计算家族成员的代数
    calculateGenerations() {
      // 创建成员映射以便快速查找
      const memberMap = new Map()
      this.familyMembers.forEach(member => {
        memberMap.set(member.id, { ...member, children: [] })
      })
      
      // 建立父子关系
      this.familyMembers.forEach(member => {
        if (member.fatherId && memberMap.has(member.fatherId)) {
          memberMap.get(member.fatherId).children.push(memberMap.get(member.id))
        }
        if (member.motherId && memberMap.has(member.motherId)) {
          memberMap.get(member.motherId).children.push(memberMap.get(member.id))
        }
      })
      
      // 找到所有没有父母的成员作为根节点
      const rootMembers = this.familyMembers.filter(member => 
        !member.fatherId && !member.motherId
      )
      
      // 为每个根节点构建家族树
      const generations = []
      rootMembers.forEach(root => {
        this.buildGenerationsForMember(memberMap.get(root.id), generations, 0)
      })
      
      this.generations = generations
    },
    
    // 为成员构建代数结构
    buildGenerationsForMember(member, generations, generationIndex) {
      // 确保代数数组足够长
      while (generations.length <= generationIndex) {
        generations.push([])
      }
      
      // 将成员添加到对应的代数中
      if (!generations[generationIndex].some(m => m.id === member.id)) {
        generations[generationIndex].push(member)
      }
      
      // 递归处理子女
      member.children.forEach(child => {
        this.buildGenerationsForMember(child, generations, generationIndex + 1)
      })
    },
    
    setSelectedFamilyTree(treeId) {
      this.selectedFamilyTree = treeId
    }
  }
})